package com.powernode.strategy.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.constant.AuthConstants;
import com.powernode.domain.LoginSysUser;
import com.powernode.mapper.LoginSysUserMapper;
import com.powernode.model.SecurityUser;
import com.powernode.strategy.LoginStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import java.util.Set;

/**
 * @Description: 管理员端登录
 * @Author: Tong Ziyu
 * @Date: 2024/10/26 11:49
 */
@Service(AuthConstants.SYS_USER_LOGIN)
@Slf4j
public class SysUserLoginImpl implements LoginStrategy {

    @Autowired
    private LoginSysUserMapper loginSysUserMapper;

    @Override
    public UserDetails realLogin(String username) {
        // 查询出用户信息

        LoginSysUser loginSysUser = loginSysUserMapper.selectOne(new LambdaQueryWrapper<LoginSysUser>()
                .eq(LoginSysUser::getUsername, username)
        );

        // 查询到用户信息
        if (ObjectUtil.isNotNull(loginSysUser)) {
            // 如果查到了,则再查询用户的权限信息
            Set<String> perms = loginSysUserMapper.selectPermsByUserId(loginSysUser.getUserId());

            SecurityUser securityUser = new SecurityUser();

            securityUser.setLoginType(AuthConstants.SYS_USER_LOGIN);
            securityUser.setPassword(loginSysUser.getPassword());
            securityUser.setUserId(loginSysUser.getUserId());
            securityUser.setStatus(loginSysUser.getStatus());
            securityUser.setShopId(loginSysUser.getShopId());


            // 判断用户是否有权限,如果有再赋值
            if (CollectionUtil.isNotEmpty(perms) && perms.size() != 0) {
                securityUser.setPerms(perms);
            }

            log.info("管理员登录用户信息:{}", securityUser);
            return securityUser;
        }
        return null;
    }
}
